package main

import (
	"fmt"
	"time"
	"gitee.com/winnie_gss/MessageBox/logs"
)

type Article struct {
	Id      int    `db:"id"`
	Title   string `db:"title"`
	Content string `db:"content"`
	ViewNum string `db:"viewnum"`
	Time    int64  `db:"time"`
	Time2   string
}

func ArticleList(sort int) []Article {
	var articleList []Article

	flag := "time"
	if sort == 1 {
		flag = "viewnum"
	}

	sql := fmt.Sprintf("select id, title, content, viewnum, time from msg_article where status='A' order by %s desc limit 10", flag)
	SelectAll(sql, &articleList)

	for k, v := range articleList {
		articleList[k].Time2 = time.Unix(v.Time, 0).Format("2006-01-02 15:04:05")
	}
	return articleList
}

func InsertArticle(title, content string) (id int64) {
	timeUx := time.Now().Unix()
	sql := "insert into msg_article(`title`, `content`, `time`) values(?, ?, ?)"
	result := UpdateDate(sql, title, content, timeUx)
	id, err := result.LastInsertId()
	logs.ErrorLog(err)
	return id
}

func ViewArticleByEditor(id int) Article {
	var article Article
	sql := "select id, title, content from msg_article where status = 'A' and id = ?"
	SelectOne(sql, &article, id)
	return article
}

func UpdateArticle(id int, title, content string) (rows int64) {
	timeUx := time.Now().Unix()
	sql := "update msg_article set title=?, content=?, time=? where id = ? and status = 'A'"
	result := UpdateDate(sql, title, content, timeUx, id)
	rows, err := result.RowsAffected()
	logs.ErrorLog(err)
	return
}

func ViewArticle(id int) Article {
	var article Article
	sql1 := "update msg_article set viewnum=viewnum+1 where status = 'A' and id = ?"
	UpdateDate(sql1, id)

	sql2 := "select id, title, content, viewnum, time from msg_article where status = 'A' and id = ?"
	SelectOne(sql2, &article, id)
	return article
}

func DeleteArticle(id int) (rows int64) {
	sql := "update msg_article set status = 'D' where id = ? and status = 'A'"
	result := UpdateDate(sql, id)
	rows, err := result.RowsAffected()
	logs.ErrorLog(err)
	return
}
